package cn.luowb.checkchat.common.util;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
@RequiredArgsConstructor
public class RedisKeyUtil {
    // 点赞防刷时间
    @Value("${check-chat.like-interval-seconds:3600}")
    public long likeIntervalSeconds;
    // 管理员token过期时间
    @Value("${check-chat.admin-token-expire-minutes:30}")
    public long adminTokenExpireMinutes;
    // 自动注入 spring.application.name 项目前缀, 避免不同项目冲突
    @Getter
    @Value("${spring.application.name}")
    private String projectPrefix;
    private final StringRedisTemplate stringRedisTemplate;

    // 管理员token
    public String buildAdminTokenKey(String token) {
        return projectPrefix + ":admin:token:" + token;
    }

    // 用户登录token
    public String buildUserLoginToken(String token) {
        return projectPrefix + ":user:token:" + token;
    }

    public String buildMessageLikeKey(Long id, String ip) {
        return projectPrefix + ":message:like:" + id + ":" + ip;
    }

    // 点赞集合的key
    public String buildLikeSetKey(int type, long objId) {
        return projectPrefix + ":like:set:" + type + ":" + objId;
    }

    // 点赞数量key
    public String buildLikeCountKey(int type, long objId) {
        return projectPrefix + ":like:count:" + type + ":" + objId;
    }

    //帖子基本信息key
    public String buildPostInfoKey(int id) {
        return projectPrefix + ":post:info:" + id;
    }


    public Set<String> scanKeys(String pattern) {
        return stringRedisTemplate.execute((RedisCallback<Set<String>>) connection -> {
            Set<String> keysTmp = new HashSet<>();
            // 使用游标进行迭代
            Cursor<byte[]> cursor = connection.keyCommands().scan(
                    ScanOptions.scanOptions()
                            .match(pattern)     // 匹配模式
                            .count(100)         // 每次迭代返回的大致数量
                            .build()
            );
            while (cursor.hasNext()) {
                keysTmp.add(new String(cursor.next()));
            }
            cursor.close();
            return keysTmp;
        });
    }
}
